<template>
  <van-popup v-model:show="visibleComputed" position="top">
    <div class="flex flex-row px-5 my-2">
      <NuxtImg class="h-6" :src="`/artopgroup/logo.png`" />
      <div class="px-3 ml-auto" @click="onClose">
        <nuxt-icon class="text-2xl" name="close" />
      </div>
    </div>
    <van-collapse v-model="activeNames">
      <van-collapse-item
        v-for="(menuItem, idx) in menuArr"
        :title="menuItem.title"
        :name="idx"
      >
        <div class="flex flex-col">
          <a
            :href="child.url"
            v-for="(child, pos) in menuItem.children"
            :key="pos"
            class="py-1"
            >{{ child.title }}</a
          >
        </div>
      </van-collapse-item>
    </van-collapse>
  </van-popup>
</template>

<script setup lang="ts">
import type { ArtopgroupResponsiveMenuItem } from ".";

const props = withDefaults(
  defineProps<{
    visible: boolean;
    menuArr?: ArtopgroupResponsiveMenuItem[];
  }>(),
  { visible: false, menuArr: () => [] }
);

const { visible } = toRefs(props);

const $emits = defineEmits<{
  "update:visible": [visible: boolean];
}>();
const visibleComputed = computed({
  get() {
    return visible.value;
  },
  set(_val: boolean) {
    $emits("update:visible", _val);
    if (_val) {
      addEscKeydownEvt();
    } else {
      removeEscKeydownEvt();
    }
  },
});
function onClose() {
  visibleComputed.value = false;
}
function onEscKeydown(event: KeyboardEvent) {
  if (event.key === "Escape") {
    visibleComputed.value = false;
  }
}
function addEscKeydownEvt() {
  if (process.client) {
    removeEscKeydownEvt();
    document.addEventListener("keydown", onEscKeydown);
  }
}
function removeEscKeydownEvt() {
  if (process.client) {
    document.removeEventListener("keydown", onEscKeydown);
  }
}
onMounted(() => {
  addEscKeydownEvt();
});
onBeforeUnmount(() => {
  removeEscKeydownEvt();
});
const activeNames = ref([0]);
const config = useRuntimeConfig();
const { BASE_PATH } = config.public;
</script>

<style scoped></style>
